package org.soenea.doitall.domain.command;

import java.util.List;
import java.util.Vector;

import org.dsrg.soenea.domain.command.CommandError;
import org.dsrg.soenea.domain.command.CommandException;
import org.dsrg.soenea.domain.command.impl.Command;
import org.dsrg.soenea.domain.helper.Helper;
import org.dsrg.soenea.domain.mapper.DomainObjectNotFoundException;
import org.dsrg.soenea.uow.UoW;
import org.soenea.doitall.domain.model.group.*;
import org.soenea.doitall.domain.model.group.mapper.*;
import org.soenea.doitall.domain.model.invite.*;
import org.soenea.doitall.domain.model.invite.mapper.*;
import org.soenea.doitall.domain.model.user.*;
import org.soenea.doitall.domain.model.user.mapper.*;

public class AcceptInviteCommand extends Command {
	public AcceptInviteCommand(Helper helper) {
		super(helper);
	}

	@Override
	public void setUp() throws CommandException {
		// TODO Auto-generated method stub
	}

	@Override
	public void process() throws CommandException {
		List<Invite> invites = new Vector<Invite>();
		try {
			try {
				long invitID = Long.parseLong(helper.getRequestAttribute("id").toString());
				long userID = (Long) helper.getSessionAttribute("UserID");
				User user = UserInputMapper.find(userID);
				long groupid = 0;

				invites = InviteInputMapper.find(userID);
				for (int i = 0; i < invites.size(); i++) {
					if (invites.get(i).getId() == invitID) {
						invites.get(i).setStatus(1);
						groupid = invites.get(i).getGroupID().getId();
						user.setGroupID(groupid);
						UoW.getCurrent().registerDirty(user);
						helper.setSessionAttribute("GroupID", groupid);
					} else {
						invites.get(i).setStatus(-1);
					}
				}
				for (int i = 0; i < invites.size(); i++) {
					UoW.getCurrent().registerDirty(invites.get(i));
				}

				UoW.getCurrent().commit();
				
				Group group = GroupInputMapper.find(groupid);
				helper.setRequestAttribute("group", group);

				List<User> users = UserInputMapper.findByGroupID(groupid);
				helper.setRequestAttribute("users", users);

			} catch (DomainObjectNotFoundException e) {
				helper.setRequestAttribute("warning",
						"Could not find a member with that username.");
			}
		} catch (Exception e) {
			throw new CommandException(e);
		}
	}

	@Override
	public void tearDown() throws CommandError {
		// TODO Auto-generated method stub
	}
}
